//
//  StrategyView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/12/27.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

@objc protocol StrategyViewDelegate {
    @objc optional func showStrategyDetails(model:NewsModel) //显示攻略详情
    @objc optional func changeStrategyViewFrame(count:Int) //改变tableView坐标
    @objc optional func stopStrategyRefresh() //停止刷新
    @objc optional func selectStrategyLabel(index:Int) //选择攻略标签
}

class StrategyView: UIView {
    
    weak var delegate : StrategyViewDelegate?
    
    fileprivate let cellId = "strategyCell"
    fileprivate var dataArray = [NewsModel]()
    
    fileprivate var tableView : UITableView!
    
    let moreButton = UIButton() //更多
    let arrowButton = UIButton() //箭头

    init() {
        super.init(frame: .zero)
        
        self.backgroundColor = UIColor.mineColor()
        
        let headView = UIView()
        headView.backgroundColor = UIColor.white
        self.addSubview(headView)
        
        let logoImageView = UIImageView()
        logoImageView.image = UIImage.init(named: "strategy")
        headView.addSubview(logoImageView)
        
        let titleLabel = UILabel()
        titleLabel.text = strategy
        titleLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        headView.addSubview(titleLabel)
        
        moreButton.setTitle(moreStrategy, for: .normal)
        moreButton.setTitleColor(UIColor.black, for: .normal)
        moreButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 14))
        headView.addSubview(moreButton)
        
        arrowButton.layer.contents = #imageLiteral(resourceName: "next").cgImage
        headView.addSubview(arrowButton)
        
        let labelView = StrategyHeadView()
        labelView.delegate = self
        self.addSubview(labelView)
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = false
        tableView.register(StrategyCell.self, forCellReuseIdentifier: cellId)
        self.addSubview(tableView)
        
        headView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
        
        logoImageView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(RATIO(maxNum: 8))
            make.width.height.equalTo(RATIO_H(maxNum: 30))
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(logoImageView.snp.right).offset(RATIO(maxNum: 8))
            make.centerY.equalTo(logoImageView)
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        arrowButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(RATIO(maxNum: -8))
            make.centerY.equalToSuperview()
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
        
        moreButton.snp.makeConstraints { (make) in
            make.right.equalTo(arrowButton.snp.left)
            make.centerY.equalToSuperview()
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        labelView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom).offset(RATIO_H(maxNum: 2))
            make.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 100))
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(labelView.snp.bottom).offset(RATIO_H(maxNum: 2))
            make.left.right.bottom.equalToSuperview()
        }
        
        getData()
    }
    
    //MARK: 加载数据
    public func getData() {
        
        KMTool.requestGetData(URLString: url_informationNews, parameters: nil, success: { (data) in
            
            let elements = ["//div[@id='content']/section/li/a","//div[@id='content']/section/li/a/img","//div[@id='content']/section/li/a/div[@class='content']/span[@class='span_top']","//div[@id='content']/section/li/a/div[@class='content']/small"]
            let attributes = ["href","src","text","text"]
            let keys = ["href","image","title","time"]
            let array = KMTool.htmlToModel(data: data, elements: elements, attributes: attributes, keys: keys)
            
            if array.count > 0 {
                self.dataArray.removeAll()
            }
            
            for item in array {
                let model = NewsModel.setModel(with: item)
                self.dataArray.append(model)
                
                if self.dataArray.count == 5 {
                    break
                }
            }
            
            self.delegate?.changeStrategyViewFrame!(count: self.dataArray.count)
            self.tableView.reloadData()
            
        }) {
            
            self.delegate?.stopStrategyRefresh!()
        }
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension StrategyView : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 100)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? StrategyCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        self.delegate?.showStrategyDetails!(model: dataArray[indexPath.row])
    }
}

extension StrategyView : StrategyHeadViewDelegate {
    
    //MARK: 选择攻略标签
    func selectStrategyLabel(index: Int) {
        self.delegate?.selectStrategyLabel!(index: index)
    }
}
